#include "FastEspnow.h"
#include "OneButton.h"
#include "FastDiode.h"

OneButton btn(0, true);
FastDiode diode(15);

/// @brief 显示所有节点
void showAllPeers()
{
    Serial.println("---------------------------- Show All Espnow Peers ----------------------------");
    Serial.printf("Native sn: %d , %d Peer has been paired \n", Espnow.sn, Espnow.peer_count);
    for (int i = 0; i < Espnow.peer_count; i++)
    {
        Serial.printf("[%d] SN: %02x ADDR: %02x:%02x:%02x:%02x:%02x:%02x  \n",
                      i + 1,
                      Espnow.peers[i].sn,
                      Espnow.peers[i].address[0], Espnow.peers[i].address[1], Espnow.peers[i].address[2],
                      Espnow.peers[i].address[3], Espnow.peers[i].address[4], Espnow.peers[i].address[5]);
    }
    Serial.println("------------------------------------------------------------------------");
}

/// @brief 接收到指令
void receiveCommand(uint8_t *mac, uint16_t sn, uint8_t commad, uint8_t len, uint8_t *data)
{
    Serial.printf("[Message] %04x COMMAND: %02x, data: ", sn, commad);
    for (int i = 0; i < len; i++)
        Serial.printf("%d(%02x) ", data[i], data[i]);
    Serial.println(" ");

    diode.flickering(500, 2);
}

void setup()
{
    Serial.begin(115200);

    // Espnow 初始化程序, 需要填入设备 SN
    Espnow.begin(0x0003);

    /* -------------------------- ESPNOW 回调函数 -------------------------- */
    // 开始扫描回调
    Espnow.attach_strat_scan_cb([]
                                { Serial.println("Start Scan! "); });
    // 结束扫描回调
    Espnow.attach_stop_scan_cb([](bool result)
                               { Serial.printf("Find %d Peer! \n", result); });
    // 设备离线通知
    Espnow.attach_PeerOffline_cb([](peer_info peer)
                                 { Serial.printf("Peer %02x Offline! \n", peer.sn); });
    // 设备上线通知
    Espnow.attach_peerOnline_cb([](peer_info peer, uint8_t *handShake_info, uint8_t handShake_info_len)
                                { Serial.printf("Peer %02x Online! \n", peer.sn); });
    // 设备挂起通知
    Espnow.attach_peerSupend_cb([](peer_info peer)
                                { Serial.printf("Peer %02x Supend! \n", peer.sn); });
    // 设备激活通知
    Espnow.attach_peerActive_cb([](peer_info peer, uint8_t *handShake_info, uint8_t handShake_info_len)
                                { Serial.printf("Peer %02x Active! \n", peer.sn); });
    // 数据接收通知
    Espnow.attach_RecMessage_cb(receiveCommand);

    /* --------------------------  按键 回调函数  -------------------------- */
    // 0 点击 显示所有节点
    btn.attachClick([]
                    { showAllPeers(); });
    // 0 双击 开始扫描
    btn.attachDoubleClick([]
                          { Espnow.scan(); });
    // 0 长按 清除所有节点
    btn.attachLongPressStop([]
                            {Serial.println("Clear all peers");Espnow.clearAllPeers(); });
}

void loop()
{
    btn.tick();
}
